<?php

namespace Fize\Third\Wechat;

use Fize\Exception\ThirdException;
use Psr\SimpleCache\CacheInterface;

/**
 * 微信接口V2
 */
class ApiV2 extends ApiAbstract
{

    /**
     * @var bool 是否初始化时马上检测AccessToken
     */
    protected $checkAccessToken = false;

    /**
     * @var array[]
     */
    protected $apis = [];


    /**
     * 构造
     * @param string              $appid     APPID
     * @param string              $appsecret APP密钥
     * @param array               $options   其他配置参数
     * @param CacheInterface|null $cache     指定缓存器
     */
    public function __construct(string $appid, string $appsecret, array $options = [], CacheInterface $cache = null)
    {
        parent::__construct($appid, $appsecret, $options, $cache);
        $this->apis = [
            'getAccessToken' => ["GET", "/cgi-bin/token?grant_type={$grant_type}&appid={$this->appid}&secret={$this->appsecret}"],
            'clearQuota'     => ["POST", "/cgi-bin/clear_quota"],
        ];
    }


    /**
     * 调用接口
     * @param string $api               接口名称
     * @param array  $params            参数
     * @param bool   $contentJsonDecode 是否对结果进行JSON解码
     * @param bool   $checkAccessToken  是否检查当前的TOKEN
     * @return array
     */
    public function call(string $api, array $params = [], bool $contentJsonDecode = true, bool $checkAccessToken = true): array
    {
        if (!isset($this->apis[$api])) {
            throw new ThirdException('Wechat', "API {$api} not found.");
        }
        $item = $this->apis[$api];
        $method = strtoupper($item[0]);
        $path = $item[1];
        if ($method == 'GET') {
            if ($params) {
                $path .= '?' . http_build_query($params);  // @todo 处理参数
            }
            return $this->httpGet($path, $contentJsonDecode, $checkAccessToken);
        } elseif ($method == 'POST') {
            return $this->httpPost($path, $params, $contentJsonDecode, $checkAccessToken);
        } else {
            throw new ThirdException('Wechat', "Method {$method} not supported.");
        }
    }
}
